package com.xzkydz;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.xzkydz.app.MyApp;
import com.xzkydz.bean.ReponseBean;
import com.xzkydz.bean.RequestBgbhBean;
import com.xzkydz.bean.WaterPumpBean;
import com.xzkydz.modle.GetRequestBgbhBean;
import com.xzkydz.modle.GetSign;
import com.xzkydz.modle.GetWaterPumpBean;
import com.xzkydz.modle.IGetRequestBgbhBean;
import com.xzkydz.modle.IGetWaterPumpBean;
import com.xzkydz.modle.Submit;
import com.xzkydz.testinterfacedemo.R;
import com.xzkydz.utils.BombInf;
import com.xzkydz.utils.DateUtils;
import com.xzkydz.utils.FileUtils;
import com.xzkydz.utils.NoDoubleClickListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.listener.BmobUpdateListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import cn.bmob.v3.update.UpdateResponse;
import cn.bmob.v3.update.UpdateStatus;

import static com.xzkydz.utils.PermisionUtils.verifyStoragePermissions;

/*
 * create at 2018/8/8
 * description:MainActivity
 */

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_show)
    EditText etShow;
    @BindView(R.id.sp_type)
    Spinner spType;
    @BindView(R.id.rbn_random)
    RadioButton rbnRandom;
    @BindView(R.id.rbn_file)
    RadioButton rbnFile;
    @BindView(R.id.rgp_choose)
    RadioGroup rgpChoose;
    @BindView(R.id.ll_pro_type)
    LinearLayout llProType;
    @BindView(R.id.sp_json)
    Spinner spJson;
    @BindView(R.id.ll_choose_json)
    LinearLayout llChooseJson;
    @BindView(R.id.et_appkey)
    EditText etAppkey;
    @BindView(R.id.ll_appkey)
    LinearLayout llAppkey;
    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.btn_clear)
    Button btnClear;
    @BindView(R.id.et_zjr)
    EditText etZjr;
    @BindView(R.id.btn_choose_files)
    Button btnChooseFiles;
    @BindView(R.id.sp_data_number)
    Spinner spDataNumber;
    private MyApp myApp;
    private IGetWaterPumpBean getWaterPumpBean;
    private IGetRequestBgbhBean getRequestBgbhBean;
    private Submit sendToServer;
    private Gson gs;
    private boolean isRandom = true;  //true : 发送随机数据
    private WaterPumpBean waterPumpBean;
    private RequestBgbhBean bgbhBean;
    private boolean mIsShowDialog = true;
    int REQUESTCODE_FROM_ACTIVITY = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        Bmob.initialize(this, BombInf.appid);
        myApp = new MyApp();
        gs = new Gson();
        getWaterPumpBean = new GetWaterPumpBean();
        getRequestBgbhBean = new GetRequestBgbhBean();
        sendToServer = new Submit();
        iniEvent();
        verifyStoragePermissions(this);
        FileUtils.CreatFolderInAPP(Environment.getExternalStorageDirectory() + "/", "测试工具");

        BmobUpdateAgent.setUpdateListener(new BmobUpdateListener() {

            @Override
            public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                // TODO Auto-generated method stub
                if (updateStatus == UpdateStatus.Yes) {//版本有更新

                } else if (updateStatus == UpdateStatus.No) {
                    try {
                       int versionCode = MainActivity.this.getPackageManager().getPackageInfo(MainActivity.this.getPackageName(), 0).versionCode;
                       String versionName = MainActivity.this.getPackageManager().getPackageInfo(MainActivity.this.getPackageName(), 0).versionName;
                        Toast.makeText(MainActivity.this, "当前版本:"+versionName + "\n版本无更新", Toast.LENGTH_SHORT).show();
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }

                } else if (updateStatus == UpdateStatus.IGNORED) {
                    Toast.makeText(MainActivity.this, "该版本已被忽略更新", Toast.LENGTH_SHORT).show();
                } else if (updateStatus == UpdateStatus.TimeOut) {
                    Toast.makeText(MainActivity.this, "APK更新查询出错或查询超时", Toast.LENGTH_SHORT).show();
                }
            }
        });

        BmobUpdateAgent.setUpdateOnlyWifi(false);
        BmobUpdateAgent.update(this);
    }

    private void iniEvent() {

        spDataNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                MyApp.getInstance().numberStr = spDataNumber.getSelectedItem() + "";
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        // 数据类型选择
        rgpChoose.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                int id = radioGroup.getCheckedRadioButtonId();
                switch (i) {
                    case R.id.rbn_random:
                        llAppkey.setVisibility(View.VISIBLE);
                        llProType.setVisibility(View.VISIBLE);
                        llChooseJson.setVisibility(View.GONE);
                        btnChooseFiles.setVisibility(View.GONE);
                        isRandom = true;
                        break;
                    case R.id.rbn_file:
                        llAppkey.setVisibility(View.GONE);
                        llProType.setVisibility(View.GONE);
                        llChooseJson.setVisibility(View.VISIBLE);
                        btnChooseFiles.setVisibility(View.VISIBLE);
                        isRandom = false;
                        break;
                }
            }
        });

        //清空显示区
        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etShow.setText("");
            }
        });

        //请求编号及数据上传
        btnSend.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {


                if (!isRandom) {
                    Toast.makeText(MainActivity.this, "功能未实现！！！", Toast.LENGTH_SHORT).show();
                    return;
                }

                try {
                    mIsShowDialog = true;
                    String appKeyStr = etAppkey.getText().toString().trim();
                    String zjrStr = etZjr.getText().toString().trim();
                    if (appKeyStr.length() == 0 || zjrStr.length() == 0) {
                        Toast.makeText(MainActivity.this, "appkey 、 主检人 不允许为空！！！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    //此处为方便直接赋值
                    MyApp.getInstance().appKeyStr = appKeyStr;
                    MyApp.getInstance().zjrStr = zjrStr;

                    waterPumpBean = getWaterPumpBean.getWaterPumpBean(MyApp.getInstance().appKeyStr);
                    bgbhBean = getRequestBgbhBean.getRequsetBgbhBean(waterPumpBean.getAppkey(), waterPumpBean.getSubmitParams().getExtra().getUserName(), waterPumpBean.getParams().getFormName());
                    StringBuilder sMsg = new StringBuilder("");
                    sMsg.append("\n\n发送请求:[ " + DateUtils.dataFormatNormal() + " ]\n");
                    sMsg.append(gs.toJson(bgbhBean));
                    sendToServer.send(bgbhBean);
                    etShow.append(sMsg);
                    etShow.setSelection(etShow.getText().length());

                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });


        //  选择文件
        btnChooseFiles.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new LFilePicker()
                        .withActivity(MainActivity.this)
                        .withRequestCode(REQUESTCODE_FROM_ACTIVITY)
                        .withStartPath("/storage/emulated/0/测试工具")//指定初始显示路径
                        .withMutilyMode(true)
                        .withNotFoundBooks("未选中任何Json文件")
                        .withMaxNum(1)
                        .withFileFilter(new String[]{".json"})
                        .start();
            }
        });


        // 设置服务器响应监听，当获取测试编号后，上传测试数据
        sendToServer.setOnBackListener(new Submit.OnBackListener() {
            @Override
            public void getResponse(final String string) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder sMsg = new StringBuilder("");
                        sMsg.append("\n\n接收:[ " + DateUtils.dataFormatNormal() + " ]\n");
                        sMsg.append(string);
                        etShow.append(sMsg);
                    }
                });

                if (mIsShowDialog) {

                    final ReponseBean res = gs.fromJson(string, ReponseBean.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (res != null && !res.getObj().equals(null)) {
                                if (res.getObj().size() != 0) {
                                    dialogList(res.getObj());
                                } else {
                                    Toast.makeText(MainActivity.this, "未分配报告编号！！！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });
                }
            }

            @Override
            public void getFailure(final String failure) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder sMsg = new StringBuilder("");
                        sMsg.append("\n\n接收:[ " + DateUtils.dataFormatNormal() + " ]\n");
                        sMsg.append(failure);
                        etShow.append(sMsg);
                    }
                });
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUESTCODE_FROM_ACTIVITY) {
                //如果是文件选择模式，需要获取选择的所有文件的路径集合
//                List<String> list = data.getStringArrayListExtra(Constant.RESULT_INFO);//Constant.RESULT_INFO == "paths"
                List<String> list = data.getStringArrayListExtra("paths");
                Toast.makeText(getApplicationContext(), "选中了" + list.size() + "个文件", Toast.LENGTH_SHORT).show();
//                如果是文件夹选择模式，需要获取选择的文件夹路径
                String path = data.getStringExtra("path");
                btnChooseFiles.setText(path);
            }
        }
    }


    private void dialogList(List<String> strings) {

        final String[] items = new String[strings.size()];
        strings.toArray(items);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择测试报告编号");
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setCancelable(false);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mIsShowDialog = false;
                waterPumpBean.getParams().setBgbh(items[which]);
                waterPumpBean.getSubmitParams().getZpsb().setBgbh(items[which]);
                waterPumpBean.getSubmitParams().getExtra().setDataId(items[which]);
                waterPumpBean.setSign(new GetSign().getUpdataSign(waterPumpBean));
                StringBuilder sMsg = new StringBuilder();
                sMsg.append("\n\n提交完整数据包:[ " + DateUtils.dataFormatNormal() + " ]\n");
                sMsg.append(gs.toJson(waterPumpBean));
                sendToServer.send(waterPumpBean);
                etShow.append(sMsg);
                etShow.setSelection(etShow.getText().length());
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mIsShowDialog = true;
                dialogInterface.dismiss();
            }
        });
        builder.create().show();
    }


    private void dialog(String oldUrlStr) {
        AlertDialog.Builder customizeDialog = new AlertDialog.Builder(MainActivity.this);
        final View dialogView = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_url, null);
        TextView oldUrl = dialogView.findViewById(R.id.tv_old_url);
        final EditText inputEdittext = dialogView.findViewById(R.id.et_input);
        oldUrl.setText("当前URL: " + oldUrlStr);
        inputEdittext.setText(oldUrlStr);
        customizeDialog.setTitle("URL更改");
        customizeDialog.setView(dialogView);

        customizeDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MyApp.getInstance().urlStr = inputEdittext.getText().toString().trim();

                        Toast.makeText(MainActivity.this, "URL 已经更改 ", Toast.LENGTH_SHORT).show();
                    }
                });
        customizeDialog.show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case R.id.action_settings:
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, WebViewActivity.class);
                startActivity(intent);
                return true;
            case R.id.action_ip:
                dialog(MyApp.getInstance().urlStr);
                return true;

            case R.id.action_updata:
                BmobUpdateAgent.forceUpdate(MainActivity.this);
                break;
        }

        return super.onOptionsItemSelected(item);
    }
}
